package com.changgou.user.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.common.constant.AuthorizeConstant;
import com.changgou.common.constant.StatusCode;
import com.changgou.common.util.BCrypt;
import com.changgou.common.util.JwtUtil;
import com.changgou.common.vo.Result;
import com.changgou.user.pojo.User;
import com.changgou.user.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/****
 * @Author:www.itheima.com
 * @Description:
 * @Date www.itheima.com
 *****/

@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    /**
    * 增加用户积分
    * @param points 积分
    * @return 操作结果
    */
    @GetMapping("/points/add")
    public Result addPoints(@RequestParam("points") int points){
        try {
            //获取用户名
            String username= SecurityContextHolder.getContext().getAuthentication().getName();

            int cont= userService.addPoints(username,points);
            if (cont>0){
                return new Result("增加用户积分成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(false, StatusCode.ERROR, "新增积分失败!");
    }


    /**
     * 根据用户名和密码登录
     * @param username
     * @param password
     * @return
     */
    @GetMapping("/login")
    public Result login(String username, String password, HttpServletResponse response){

        User user = userService.findById(username);

        /**
        * 参数1：明文密码
        * 参数2：加密密文
        */
        if (user!=null&& BCrypt.checkpw(password,user.getPassword())) {
            Map<String,Object> info=new HashMap<>();
            info.put("username",username);
            info.put("password",password);
            info.put("success","SUCCESS");
            //签发令牌
            String token= JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(info),null);

            //将令牌存入cookie中
            Cookie cookie = new Cookie(AuthorizeConstant.AUTHORIZE_TOKEN, token);
            response.addCookie(cookie);

            return new Result("登录成功！",token);
        }
        return new Result("用户名或密码错误！");
    }

    /***
     * User分页条件搜索实现
     * @param user: 查询条件
     * @param page:当前页
     * @param size:每页显示多少条
     * @return 查询结果
     */
    @PostMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo<User>> findPage(@RequestBody(required = false)  User user, @PathVariable  int page, @PathVariable  int size){
        //调用UserService实现分页条件查询User
        PageInfo<User> pageInfo = userService.findPage(user, page, size);
        return new Result<PageInfo<User>>("查询成功！", pageInfo);
    }

    /***
     * User分页搜索实现
     * @param page:当前页
     * @param size:每页显示多少条
     * @return 查询结果
     */
    @GetMapping(value = "/search/{page}/{size}" )
    public Result<PageInfo<User>> findPage(@PathVariable  int page, @PathVariable  int size){
        //调用UserService实现分页查询User
        PageInfo<User> pageInfo = userService.findPage(page, size);
        return new Result<PageInfo<User>>("查询成功！", pageInfo);
    }

    /***
     * 多条件搜索品牌数据
     * @param user 查询条件
     * @return 查询结果
     */
    @PostMapping(value = "/search" )
    public Result<List<User>> findList(@RequestBody(required = false)  User user){
        //调用UserService实现条件查询User
        List<User> list = userService.findList(user);
        return new Result<List<User>>("查询成功！", list);
    }

    /***
     * 根据ID删除品牌数据
     * @param id 主键
     * @return 查询结果
     */
    @PreAuthorize("hasAnyAuthority('superman')")
    @DeleteMapping(value = "/{id}" )
    public Result delete(@PathVariable String id){
        //调用UserService实现根据主键删除
        userService.delete(id);
        return new Result(true, StatusCode.OK, "删除成功！");
    }

    /***
     * 修改User数据
     * @param user 更新对象
     * @return 操作结果
     */
    @PutMapping
    public Result update(@RequestBody  User user){
        //调用UserService实现修改User
        userService.update(user);
        return new Result(true, StatusCode.OK, "修改成功！");
    }

    /***
     * 新增User数据
     * @param user 新增对象
     * @return 操作结果
     */
    @PostMapping
    public Result add(@RequestBody  User user){
        //调用UserService实现添加User
        userService.add(user);
        return new Result(true, StatusCode.OK, "添加成功！");
    }

    /***
     * 根据ID查询User数据
     * @param id 主键
     * @return 查询结果
     */
    @GetMapping({"/{id}","/load/{id}"})
    public Result<User> findById(@PathVariable String id){
        //调用UserService实现根据主键查询User
        User user = userService.findById(id);
        return new Result<User>("查询成功！", user);
    }

    /***
     * 查询User全部数据
     * @return 查询结果
     */
    @GetMapping
    public Result<List<User>> findAll(HttpServletRequest request){

        String claim = request.getHeader(AuthorizeConstant.AUTHORIZE_TOKEN);
        System.out.println("---------------authorization = " +claim);

        //调用UserService实现查询所有User
        List<User> list = userService.findAll();
        return new Result<List<User>>("查询成功！", list);
    }
}
